#include "NamedPipeServer.h"

int main(int argc, char * argv)
{
	CreateNamedPipeInServer();

	//Write to named pipe from server
	NamedPipeWriteInServer();

	//Recv data from client
	NamedPipeReadInServer();

	system("pause");
}


void CreateNamedPipeInServer()
{
	HANDLE                    hEvent;
	OVERLAPPED                ovlpd;

	//Create named pipe
	//Create shuangxiang & chongdie named pipe
	hNamedPipe = CreateNamedPipe(pPipeName, 
		PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED, 
		0, 1, 1024, 1024, 0, NULL);

	if(INVALID_HANDLE_VALUE == hNamedPipe)
	{
		hNamedPipe = NULL;
		cout<<"Create named pipe failed..."<<endl<<endl;
		return;
	}

	//Add event handler to wait for client to connect

	hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
	if(!hEvent)
	{
		cout<<"Create event handler failed..."<<endl<<endl;
		return;
	}

	memset(&ovlpd, 0, sizeof(OVERLAPPED));


	ovlpd.hEvent = hEvent;

	//Wait for client to connect
	if(!ConnectNamedPipe(hNamedPipe, &ovlpd))
	{
		if(ERROR_IO_PENDING != GetLastError())
		{
			CloseHandle(hNamedPipe);
			CloseHandle(hEvent);

			cout<<"Wait for client to connect..."<<endl<<endl;
			return;
		}
	}

	//Wait for event-hEvent failed
	if(WAIT_FAILED == WaitForSingleObject(hEvent, INFINITE))
	{
		CloseHandle(hNamedPipe);
		CloseHandle(hEvent);

		cout<<"Wait for event-hEvent failed..."<<endl<<endl;
		return;
	}

	CloseHandle(hEvent);
}


void NamedPipeReadInServer()
{
	TCHAR*            pReadBuf;
	DWORD            dwRead;

	pReadBuf = new TCHAR[_tcslen(pStr) + 1];
	memset(pReadBuf, 0, _tcslen(pStr) + 1);

	//Read from pipe
	if(!ReadFile(hNamedPipe, pReadBuf, _tcslen(pStr), &dwRead, NULL))
	{
		delete []pReadBuf;

		cout<<"Read data failed..."<<endl<<endl;
		return;
	}
	cout<<"Read data success:   "<<pReadBuf<<endl<<endl;
}


void NamedPipeWriteInServer()
{
	DWORD            dwWrite;

	//Write to named pipe
	if(!WriteFile(hNamedPipe, pStr, _tcslen(pStr), &dwWrite, NULL))
	{
		cout<<"Write data failed..."<<endl<<endl;
		return;
	}
	cout<<"Write data success:   "<<pStr<<endl<<endl;
}